package com.avic.rong.transform.activity;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.listener.EndlessRecyclerOnScrollListener;
import com.avic.rong.search.adapter.homePageAdapter.TransformAdapter;
import com.avic.rong.transform.api.TransformApi;
import com.avic.rong.transform.bean.HallBean;
import com.avic.rong.transform.bean.HallDictBean;
import com.avic.rong.transform.bean.SupplyAndDemandBean;
import com.avic.rong.transform.fragment.DemandAttrFragment;
import com.avic.rong.transform.fragment.SupplyAttrFragment;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.EditUtils;
import com.avic.rong.utils.StringUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.CircleProgressDialog;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TransformListActivity extends BaseActivity implements SearchFilterViewTransform.FilterInterface, OnRefreshListener, OnLoadMoreListener {


    public static final String ARG_TRANSFORMTYPE = "transformType";
    public static final String ARG_SORT = "sort";
    public static final String ARG_CATID = "catId";
    public static final String ARG_KEYWORD = "keyword";


    @BindView(R.id.edit_keyword)
    EditText edit_keyword;//关键词

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;//loading
    @BindView(R.id.goods_sort_bz_DrawerLayout)
    DrawerLayout goods_sort_bz_DrawerLayout;
    @BindView(R.id.recycler_list)
    RecyclerView recycler_list;

    @BindView(R.id.frame_attr)
    FrameLayout frame_attr;
    @BindView(R.id.ll_group)
    LinearLayout ll_group;
    @BindView(R.id.filterViewTransform)
    SearchFilterViewTransform filterViewTransform;

    //type group start
    private int transformType = 0;//0.需求 1.供应

    private TransformApi transformApi;

    private TransformAdapter transformAdapter;

    private Fragment currentFragment = new Fragment();
    private DemandAttrFragment demandAttrFragment;
    private SupplyAttrFragment supplyAttrFragment;

    private int sort = 0;
    private Integer catId;
    private String keyword;

    public List<HallDictBean> dictBeanList = new ArrayList<>();


    @Override
    protected int getContentViewId() {
        return R.layout.activity_transform_list;
    }

    @Override
    protected void initView() {

        keyword = getIntent().getStringExtra("keyword");
        transformType = getIntent().getIntExtra(ARG_TRANSFORMTYPE, 0);
        sort = getIntent().getIntExtra(ARG_SORT, 0);
        keyword = getIntent().getStringExtra(ARG_KEYWORD);
        catId = getIntent().getIntExtra(ARG_CATID, 0);


        goods_sort_bz_DrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                isRefresh = false;
                currentPageNumber = 1;
                loading_layout.setStatus(LoadingLayout.LOADING);
                transformApi.setPageNo(currentPageNumber);
                HttpManager.getInstance().doHttpDeal(transformApi);
            }

            @Override
            public void onReturn(View v) {
                onBackPressed();
            }
        });


        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        filterViewTransform.setFilterInterface(this);


        //recycler_list初始化
        LinearLayoutManager layoutManager = new LinearLayoutManager(TransformListActivity.this);
        recycler_list.setLayoutManager(layoutManager);


        endLessLoadMore(recycler_list, layoutManager);//预加载开启
        DividerItemDecoration divider = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(context, R.drawable.divider_05_pix));
        recycler_list.addItemDecoration(divider);

        transformAdapter = new TransformAdapter(this, transformType);
        recycler_list.setAdapter(transformAdapter);


        transformApi = new TransformApi(TransformListActivity.this, searchAllListener, transformType);

        if (transformType == 1) {
//            transformApi.setArgument(1, 1, 0);
        } else if (transformType == 2) {
//            transformApi.setArgument(1, 2, 0);
        }
        transformApi.setSort(sort);
        filterViewTransform.switchRadioButton(sort);

//        if (!StringUtils.isEmpty(keyword)) {
//            transformApi.setKeyword(keyword);
//            edit_keyword.setText(keyword);
//        }
//        HallDictInfoApi hallDictInfoApi = new HallDictInfoApi(TransformListActivity.this, dictInfoListener);
        HttpManager.getInstance().doHttpDeal(transformApi);


        //右侧抽屉视图
        if (transformType == 0) {//需求
            initDemandAttrFragment();
            switchFragment(demandAttrFragment);
        } else if (transformType == 1) {//供应
            filterViewTransform.hiddenEndTime();
            initSupplyAttrFragment();
            switchFragment(supplyAttrFragment);
        }

        initEditListener();

    }


    private void initDemandAttrFragment() {
        demandAttrFragment = DemandAttrFragment.getInstance(this);
        demandAttrFragment.setClickInterface(new DemandAttrFragment.ClickInterface() {//抽屉OK确定
            @Override
            public void clickOK(String attrPro) {
                Integer typeId = null;
                catId = null;
                String[] attrArray = attrPro.split("&");
                for (int index = 0; index < attrArray.length; index++) {
                    String tempStr = attrArray[index];
                    if (tempStr.contains("10000")) {
                        String[] tempArr = tempStr.split("__");
                        catId = Integer.parseInt(tempArr[1]);
                    } else if (tempStr.contains("20000")) {
                        String[] tempArr = tempStr.split("__");
                        typeId = Integer.parseInt(tempArr[1]);
                    }
                }


                isRefresh = true;
                currentPageNumber = 1;
                transformApi.setCatId(catId);
                transformApi.setTypeId(typeId);
                transformApi.setPageNo(currentPageNumber);
                HttpManager.getInstance().doHttpDeal(transformApi);

                if (EditUtils.isSoftShowing(TransformListActivity.this)) {
                    EditUtils.hideSystemSoftKeyboard(TransformListActivity.this);
                }
                goods_sort_bz_DrawerLayout.closeDrawers();
            }
        });
    }

    private void initSupplyAttrFragment() {
        if (supplyAttrFragment == null) {
            supplyAttrFragment = SupplyAttrFragment.getInstance(this);
            supplyAttrFragment.setClickInterface(new SupplyAttrFragment.ClickInterface() {
                @Override
                public void clickOK(String attrPro) {
                    Integer typeId = null;
                    catId = null;
                    String[] attrArray = attrPro.split("&");
                    for (int index = 0; index < attrArray.length; index++) {
                        String tempStr = attrArray[index];
                        if (tempStr.contains("10000")) {
                            String[] tempArr = tempStr.split("__");
                            catId = Integer.parseInt(tempArr[1]);
                        } else if (tempStr.contains("20000")) {
                            String[] tempArr = tempStr.split("__");
                            typeId = Integer.parseInt(tempArr[1]);
                        }
                    }


                    isRefresh = true;
                    currentPageNumber = 1;
                    transformApi.setPageNo(currentPageNumber);
                    transformApi.setTypeId(typeId);
                    transformApi.setCatId(catId);

                    HttpManager.getInstance().doHttpDeal(transformApi);
                    CircleProgressDialog.showDialog(context);
                    if (EditUtils.isSoftShowing(TransformListActivity.this)) {
                        EditUtils.hideSystemSoftKeyboard(TransformListActivity.this);
                    }
                    goods_sort_bz_DrawerLayout.closeDrawers();
                }
            });
        }


    }


    /**
     * 顶部Edit搜索
     */
    private void initEditListener() {
        edit_keyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {

                    //关闭软键盘
                    EditUtils.showORhideSoftKeyboard(TransformListActivity.this);
                    keyword = edit_keyword.getText().toString();
                    if (StringUtils.isEmpty(keyword)) {
                        ToastTools.showToast("请输入关键词!");
                        return true;
                    }

                    isRefresh = true;
                    currentPageNumber = 1;
                    transformApi.setKeyword(keyword.trim());
                    transformApi.setPageNo(currentPageNumber);
                    HttpManager.getInstance().doHttpDeal(transformApi);
                    return true;
                }
                return false;
            }
        });
    }


    //获取标准数据监听
    HttpOnNextListener<BaseResultEntity> searchAllListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            CircleProgressDialog.closeDialog();

            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(subjects.getCode())) {
                ToastTools.showToast(context, subjects.getMsg());
                Logger.e("cjx", "biaozhun数据：" + subjects.getMsg());
                return;
            }

            HallBean.PageBean pageBean = ((HallBean) subjects.getData()).getPage();
            List<SupplyAndDemandBean> demandBeanList = pageBean.getList();


            if (isRefresh) {
                transformAdapter.getBeanList().clear();
            }
            transformAdapter.setBeanList(demandBeanList);

            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }

            if (transformAdapter.getBeanList().size() == 0) {
                loading_layout.setStatus(LoadingLayout.EMPTY);
            } else {
                loading_layout.setStatus(LoadingLayout.SUCCESS);
            }
        }


        @Override
        public void onError(final Throwable e) {
            CircleProgressDialog.closeDialog();
            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
            Logger.e("cjx", "bz拿到数据" + e.getMessage());
        }
    };


    @OnClick({R.id.img_direct, R.id.img_back, R.id.img_delete})
    public void clickListener(View view) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.img_back:
                onBackPressed();
                break;
            case R.id.img_direct:
                showPopup(this,findViewById(R.id.ll_root_top));
//                startActivity(GoodsSortActivity.getIntent(context));

                break;
            case R.id.img_delete://清空关键词
                edit_keyword.setText(ConstantsUtils.EMPTY_STR);
                keyword = ConstantsUtils.EMPTY_STR;
                transformApi.setKeyword(keyword);
                HttpManager.getInstance().doHttpDeal(transformApi);
                break;
        }
    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        currentPageNumber = currentPageNumber + 1;
        transformApi.setPageNo(currentPageNumber);
        HttpManager.getInstance().doHttpDeal(transformApi);

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isRefresh = true;
        currentPageNumber = 1;
        transformApi.setPageNo(currentPageNumber);
        HttpManager.getInstance().doHttpDeal(transformApi);
    }


    @Override
    public void clickSort(int sort) {//排序监听
        isRefresh = true;
        currentPageNumber = 1;
        transformApi.setPageNo(currentPageNumber);
        transformApi.setSort(sort);
        Logger.i("-------------------------kkksort:" + sort);
        HttpManager.getInstance().doHttpDeal(transformApi);
    }

    @Override
    public void openFilter() {//打开抽屉
        goods_sort_bz_DrawerLayout.openDrawer(GravityCompat.END);
    }


    /**
     * 预加载
     *
     * @param recyclerView
     * @param layoutManager
     */
    private void endLessLoadMore(RecyclerView recyclerView, LinearLayoutManager layoutManager) {
        recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore(int current_page) {
                isRefresh = false;
                currentPageNumber = currentPageNumber + 1;
                transformApi.setPageNo(currentPageNumber);
                HttpManager.getInstance().doHttpDeal(transformApi);

            }
        });
    }


    private void switchFragment(Fragment targetFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {//如果要显示的targetFragment没有添加过
            transaction
                    .hide(currentFragment)//隐藏当前Fragment
                    .add(R.id.frame_attr, targetFragment, targetFragment.getClass().getName())//添加targetFragment
                    .commit();
        } else {//如果要显示的targetFragment已经添加过
            transaction//隐藏当前Fragment
                    .hide(currentFragment)
                    .show(targetFragment)//显示targetFragment
                    .commit();
        }
        //更新当前Fragment为targetFragment
        currentFragment = targetFragment;
    }


    public static Intent getIntent(Context context, int type) {
        Intent intent = new Intent(context, TransformListActivity.class);
        intent.putExtra(ARG_TRANSFORMTYPE, type);
        return intent;
    }


    @Override
    protected void addListener() {

    }


}
























